﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System.Threading.Tasks;

namespace SignalRChart.Models
{
    [HubName("MyHub")]
    public class MyHub : Hub
    {
        //声明静态变量存储当前在线用户

        public static Dictionary<string, string> ConnectedIds = new Dictionary<string, string>();

        public void sendAll(string user, string message)
        {
            //处理服务端完成后调用客户端的方法
            Clients.All.showMessage(user, message);
        }

        public void sendToUser(string id, string user, string message)
        {
            //处理服务端完成后调用客户端的方法
            Clients.Client(id).secretMessage(user, message);
        }

        public void sendToGroup(string id, string user, string message)
        {
            //分组的就不演示了，不难，
        }

        //用户进入页面时执行的（连接操作）
        public void userConnected(string name)
        {
            //进行编码，防止XSS攻击
            name = HttpUtility.HtmlEncode(name);

            //将用户连接ID 和用户名存入字典，
            if (!ConnectedIds.ContainsKey(Context.ConnectionId))
            {
                ConnectedIds.Add(Context.ConnectionId, name);
            }

            //将所有登录用户列表传递回去给新登录的用户
            Clients.Caller.getUser(ConnectedIds.Select(p => new { id = p.Key, name = p.Value }).ToList());

            //同时将刚登录的用户信息反馈给老用户
            Clients.Others.addUser(Context.ConnectionId, name);

            //发送信息给其他人
            Clients.Others.hello(name);
        }

        //发送信息给特定人
        public void secretMessage(string toID, string message)
        {
            message = HttpUtility.HtmlEncode(message);
            KeyValuePair<string, string> user = ConnectedIds.Where(p => p.Key == Context.ConnectionId).FirstOrDefault();
            Clients.Client(toID).sendMessage(user.Value, message);
        }

        //当使用者断线时执行
        public override Task OnDisconnected(bool stopCalled)
        {
            KeyValuePair<string, string> user = ConnectedIds.Where(a => a.Key == Context.ConnectionId).SingleOrDefault();
            //当使用者离开时，移除在清单内的ConnectionId
            Clients.All.removeUser(user.Key, user.Value);

            ConnectedIds.Remove(Context.ConnectionId);
            return base.OnDisconnected(stopCalled);
        }
    }
}